#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
批量验证评论ID有效性
这个脚本会测试从评论列表API返回的所有评论ID，
验证哪些可以用于回复功能。
"""

import json
import requests
import time

def test_comment_nearby():
    """获取评论列表"""
    try:
        print("🔍 =============== 获取评论列表 ===============")
        
        # 发送评论列表请求
        data = {
            "latitude": 39.915,
            "longitude": 116.404,
            "radius": 50.0,
            "limit": 20,
            "timestamp": int(time.time())
        }
        
        response = requests.post(
            "http://124.71.77.44:2233/comments/nearby/",
            json=data,
            timeout=10
        )
        
        print(f"📊 HTTP状态: {response.status_code}")
        
        if response.status_code == 200:
            response_data = response.json()
            if response_data.get('status') == 'success':
                comments = response_data.get('data', [])
                print(f"✅ 获取到 {len(comments)} 个评论")
                
                comment_ids = [comment.get('commentId') for comment in comments if 'commentId' in comment]
                print(f"📋 评论ID列表: {comment_ids}")
                
                return comment_ids
            else:
                print(f"❌ 评论列表查询失败: {response_data.get('message', '未知错误')}")
        else:
            print(f"❌ HTTP请求失败: {response.status_code}")
            print(f"响应内容: {response.text}")
        
        return []
        
    except Exception as e:
        print(f"💥 获取评论列表异常: {e}")
        return []

def validate_comment_detail(comment_id):
    """验证单个评论ID的有效性"""
    try:
        print(f"\n🔍 验证评论ID: {comment_id}")
        
        # 使用明文方式查询评论详情
        data = {
            "commentId": comment_id,
            "timestamp": int(time.time())
        }
        
        response = requests.post(
            "http://124.71.77.44:2233/comments/detail/",
            json=data,
            timeout=10
        )
        
        print(f"   📊 HTTP状态: {response.status_code}")
        
        if response.status_code == 200:
            response_data = response.json()
            status = response_data.get('status', 'unknown')
            message = response_data.get('message', '')
            
            if status == 'success':
                print(f"   ✅ 评论ID {comment_id} 有效 - 可以添加回复")
                return True
            elif status == 'error':
                print(f"   ❌ 评论ID {comment_id} 无效 - {message}")
                return False
            else:
                print(f"   ⚠️ 评论ID {comment_id} 状态未知 - {status}")
                return False
        else:
            print(f"   💥 HTTP请求失败: {response.status_code}")
            print(f"   响应内容: {response.text}")
            return False
        
    except Exception as e:
        print(f"   💥 验证评论ID {comment_id} 异常: {e}")
        return False

def test_comment_reply(comment_id):
    """测试评论回复功能"""
    try:
        print(f"\n💬 测试评论ID {comment_id} 的回复功能")
        
        data = {
            "commentId": comment_id,
            "userId": 62,
            "userNickname": "测试用户",
            "replyContent": "这是Python脚本的测试回复",
            "timestamp": int(time.time())
        }
        
        response = requests.post(
            "http://124.71.77.44:2233/comments/replies",
            json=data,
            timeout=10
        )
        
        print(f"   📊 HTTP状态: {response.status_code}")
        
        if response.status_code == 200:
            response_data = response.json()
            status = response_data.get('status', 'unknown')
            message = response_data.get('message', '')
            
            if status == 'success':
                print(f"   ✅ 评论ID {comment_id} 回复成功")
                return True
            else:
                print(f"   ❌ 评论ID {comment_id} 回复失败 - {message}")
                return False
        else:
            print(f"   💥 HTTP请求失败: {response.status_code}")
            return False
        
    except Exception as e:
        print(f"   💥 测试回复异常: {e}")
        return False

def main():
    """主函数"""
    print("🧪 =============== 批量验证评论ID有效性 ===============")
    
    # 1. 获取所有评论ID
    comment_ids = test_comment_nearby()
    
    if not comment_ids:
        print("❌ 没有获取到任何评论ID，无法继续验证")
        return
    
    print(f"\n📋 准备验证 {len(comment_ids)} 个评论ID")
    
    valid_ids = []
    invalid_ids = []
    
    # 2. 验证每个评论ID的详情查询
    print("\n🔍 =============== 详情查询验证 ===============")
    for comment_id in comment_ids:
        if validate_comment_detail(comment_id):
            valid_ids.append(comment_id)
        else:
            invalid_ids.append(comment_id)
        time.sleep(0.5)  # 避免请求过快
    
    # 3. 对有效的ID测试回复功能
    print("\n💬 =============== 回复功能验证 ===============")
    reply_success_ids = []
    
    for comment_id in valid_ids[:3]:  # 只测试前3个，避免垃圾数据
        if test_comment_reply(comment_id):
            reply_success_ids.append(comment_id)
        time.sleep(1)  # 回复测试间隔更长一些
    
    # 4. 输出总结
    print("\n📊 =============== 验证结果总结 ===============")
    print(f"🔢 总评论数: {len(comment_ids)}")
    print(f"✅ 详情查询有效: {len(valid_ids)} 个")
    print(f"❌ 详情查询无效: {len(invalid_ids)} 个")
    print(f"💬 回复功能测试: {len(reply_success_ids)} 个成功")
    
    if valid_ids:
        print(f"✅ 推荐使用这些评论ID进行回复测试: {valid_ids}")
    else:
        print("❌ 没有找到有效的评论ID")
    
    if invalid_ids:
        print(f"⚠️ 这些评论ID无效或已被删除: {invalid_ids}")
    
    print("🏁 =============== 批量验证完成 ===============")

if __name__ == "__main__":
    main()
